
package com.gamatechno.solodestinationnew;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.gamatechno.solodestinationnew.entity.E_Komentar;
import com.gamatechno.solodestinationnew.helper.JSONHelper;
import com.gamatechno.solodestinationnew.utils.CircleTransform;
import com.gamatechno.solodestinationnew.utils.Utils;
import com.gamatechno.solodestinationnew.utils.Webservice;
import com.squareup.picasso.Picasso;

public class GalleryDetailActivity extends BaseActivity implements OnClickListener {

    private ImageView imgDetail;
    private Bundle data;
    private EditText etKomen;
    private ImageView btnKomen;
    private TextView uploadBy;
    private LinearLayout containerComment;
    private List<E_Komentar> listKomentar;
    private LayoutInflater inflater;
    private int id;
    private HashMap<String, String> params;
    private ProgressDialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_detail);

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        inflater = LayoutInflater.from(this);

        data = getIntent().getExtras();
        id = data.getInt("id");

        imgDetail = (ImageView) findViewById(R.id.img_gallery_detail);
        containerComment = (LinearLayout) findViewById(R.id.container_komentar_photo);
        btnKomen = (ImageView) findViewById(R.id.btnKomenPhoto);
        uploadBy = (TextView) findViewById(R.id.uploaded_by_detail);
        etKomen = (EditText) findViewById(R.id.et_komen);

        data = getIntent().getExtras();
        if (data != null) {
            imgDetail.setImageBitmap(Utils.decodeBase64(data.getString("img")));
            uploadBy.setText(data.getString("upload"));
        }

        btnKomen.setOnClickListener(this);

        getKomen(Webservice.GET_COMMENT_PHOTO(id));
    }

    private void generateKomen(List<E_Komentar> listKomentar2) {
        if (containerComment.getChildCount() > 0)
            containerComment.removeAllViews();

        for (E_Komentar komen : listKomentar2) {
            View view = inflater.inflate(R.layout.item_comment_gallery, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            params.setMargins(0, 0, 0, 10);

            view.setLayoutParams(params);
            final TextView name = (TextView) view.findViewById(R.id.comment_name_gallery);
            final TextView date = (TextView) view.findViewById(R.id.comment_date_gallery);
            final TextView comment = (TextView) view.findViewById(R.id.comment_gallery);
            final ImageView thumbUser = (ImageView) view
                    .findViewById(R.id.thumb_user_comment_gallery);

            name.setText(komen.getName());
            date.setText(komen.getDate());
            comment.setText(komen.getKomentar());

            getImageUserFB(Webservice.GET_FB_PHOTO(komen.getIduser()), thumbUser);

            containerComment.addView(view);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        // getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void uploadKoment(String URL) {
        StringRequest request = new StringRequest(Request.Method.POST,
                URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String arg0) {
                        pDialog.dismiss();
                        etKomen.setText("");
                        Utils.TRACE(
                                "GalleryDetailActivity.uploadKoment(...).new StringRequest() {...}",
                                "uploadKoment : " + arg0);
                        getKomen(Webservice.GET_COMMENT_PHOTO(id));
                    }
                },
                new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        pDialog.dismiss();
                        Utils.TRACE(
                                "GalleryDetailActivity.uploadKoment(...).new StringRequest() {...}",
                                "uploadKoment : " + arg0);
                        Utils.showVolleyError(GalleryDetailActivity.this, arg0);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                params = new HashMap<String, String>();
                String name = Utils.getDataStringFromSP(
                        GalleryDetailActivity.this, Utils.PREF_USERNAME);

                params.put("method", "insertCommentPhoto");
                params.put("format", "json");
                params.put("gallery_id", "" + id);
                params.put("user_id",
                        Utils.getDataStringFromSP(GalleryDetailActivity.this, Utils.PREF_FB_ID));
                params.put("name", name);
                Utils.TRACE("GalleryDetailActivity.uploadKoment(...).new StringRequest() {...}",
                        "getParams : " + etKomen.getText().toString());
                params.put("comment", "" + etKomen.getText().toString());
                return params;
            }
        };
        pDialog.show();
        BaseApplication.getInstance().addToRequestQueue(request, "Gallery");
    }

    private void getKomen(String URL) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject obj) {
                        Utils.TRACE("GalleryDetailActivity.getKomen(...).new Listener() {...}",
                                "onResponse : " + obj.toString());
                        try {
                            if (obj.getInt("status") == 200) {
                                if (obj.getJSONArray("result").length() > 0) {

                                    if (listKomentar != null)
                                        if (listKomentar.size() > 0)
                                            listKomentar.clear();

                                    listKomentar = JSONHelper.getListKomentarPhoto(obj
                                            .getJSONArray("result"));
                                    generateKomen(listKomentar);
                                }
                            }
                        } catch (JSONException e) {
                            Utils.TRACE("GalleryDetailActivity.getKomen(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE(
                                "GalleryDetailActivity.getKomen(...).new ErrorListener() {...}",
                                "getKomen : " + error.getMessage());
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, "GALLERY");

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v == btnKomen) {
            // post komen
            if (Utils.getDataBooleanFromSP(GalleryDetailActivity.this, Utils.PREF_ISLOGIN)) {
                if (!TextUtils.isEmpty(etKomen.getText().toString())) {
                    uploadKoment(Webservice.POST_PHOTO_GALLERY);
                } else {
                    Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "Need Login", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void getImageUserFB(String URL, final ImageView img) {
        Utils.TRACE("DetailLocationActivity", "getImageUserFB : ");
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
                URL,
                null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject obj) {
                        try {
                            JSONObject objectData = obj.getJSONObject("data");

                            Picasso.with(GalleryDetailActivity.this)
                                    .load(objectData.getString("url"))
                                    .transform(new
                                            CircleTransform()).into(img);
                        } catch (JSONException e) {
                            Utils.TRACE(
                                    "DetailLocationActivity.getImageUserFB(...).new Listener() {...}",
                                    "onResponse : " + e.getMessage());
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Utils.TRACE(
                                "DetailLocationActivity.getImageUserFB(...).new ErrorListener() {...}",
                                "getImageUserFB : " + error.getMessage());
                    }
                });
        BaseApplication.getInstance().addToRequestQueue(request, "img");
    }

}
